<?php


namespace App\Services;

use App\Models\SmsCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use \Exception;

class SmsService
{
    public function list(Request $request)
    {
        $model = DB::table('xpel_sms_content')->orderBy('id', 'desc');
        $model = filterByColumns($model, ['english_content', 'traditional_chinese_content', 'simplified_chinese_content']);

        $data = $model->get();
        if (empty($data)) {
            return [];
        }

        return $data;
    }

    public function save(Request $request, int $id)
    {
        $user_id = session('admin.id');
        $english_sign = $request->input('english_sign');
        $simplified_chinese_sign = $request->input('simplified_chinese_sign');
        $traditional_chinese_sign = $request->input('traditional_chinese_sign');
        $simplified_chinese_content = $request->input('simplified_chinese_content');
        $traditional_chinese_content = $request->input('traditional_chinese_content');
        $english_content = $request->input('english_content');

        if (empty($english_content) || empty($traditional_chinese_content) || empty($simplified_chinese_content)) {
            return [];
        }

        $saveData = [
            'creator_id' => $user_id,
            'english_sign'  => $english_sign,
            'simplified_chinese_sign' => $simplified_chinese_sign,
            'traditional_chinese_sign' => $traditional_chinese_sign,
            'english_content' => $english_content,
            'traditional_chinese_content' => $traditional_chinese_content,
            'simplified_chinese_content' => $simplified_chinese_content,
            'status' => 1,
        ];

        if (!empty($id)) {
            return DB::table('xpel_sms_content')->where('id', $id)->update($saveData);
        }

        return DB::table('xpel_sms_content')->insertGetId($saveData);
    }

    public function getSmsContent(int $id)
    {
        return DB::table('xpel_sms_content')->where('id', $id)->first();
    }

    public function getContent(int $langType, int $yearId, string $make, string $model)
    {
        $content = DB::table('xpel_sms_content')->orderBy('id', 'desc')->first();
        if (empty($content)) {
            return '';
        }

        if ($langType === 3) {
            $smsContent = "【" . $content->english_sign . "】" . $content->english_content;
        } else if ($langType === 2) {
            $smsContent = "【" . $content->traditional_chinese_sign . "】" . $content->traditional_chinese_content;
        } else {
            $smsContent = "【" . $content->simplified_chinese_sign . "】" . $content->simplified_chinese_content;
        }

        $smsContent = str_replace(['#year#', '#model#', '#make#'], [$yearId, $model, $make], $smsContent);

        return $smsContent;
    }

    /**
     * 发送短信
     *
     * @param array $notice
     * @return array|string[]
     * @throws \Exception
     */
    public function sendSms(array $notice)
    {
        if (empty($notice) || empty($notice['mobile'])) {
            throw new Exception('手机号不能为空');
        }
        $logs = alogs('短信', '微信绑定账号', '', null, $notice);

        $ext = $notice['extension'] ?? '+86';
        $mobile = $notice['mobile'] ?? '';
        if (empty($ext) || !in_array($ext, ['+86', '+886', '+853', '+852'])) {
            throw new Exception('地区号不能为空！');
        }

        $smsCode = mt_rand(100000, 999999);

        $model = new SmsCode();
        $model->ip = request()->ip();
        $model->ext = $ext;
        $model->phone = $mobile;
        $model->type = 3;
        $model->code = $smsCode;
        $model->status = 0;
        $model->save();

        if ($ext === '+86') {
            $content = '【XPEL保护膜认证店】验证码：' . $smsCode . '。尊敬的用户，您正在办理质保查询手机号码绑定操作，切勿将验证码告知他人。';
            $obj = message_sms_send($ext, $mobile, $content);
        } else {
            $content = '【XPEL保护膜认证店】验证码：' . $smsCode . '。尊敬的用户，您正在办理质保查询手机号码绑定操作，切勿将验证码告知他人。';
            $obj = international_sms_send($ext, $mobile, $content);
        }

        $params = [
            'ext' => $ext,
            'mobile' => $mobile,
            'content' => $content,
            'res' => $obj['data'] ?? '',
        ];

        $logs->new = $params;
        $logs->save();

        if (!empty($obj['status']) && $obj['status'] === 'SUCCESS') {
            return [
                'status'    =>'SUCCESS',
                'msg'       => '成功！',
            ];
        }

        throw new Exception('发送短信失败');
    }

    public function checkSmsCode(string $mobile, string $ext, int $type, string $smsCode)
    {
        $smsCodeRecord = DB::table('sms_code')->where('phone', $mobile)
            ->where('ext', $ext)->where('type', $type)
            ->where('created_at', '>=', strtotime('-1 min'))
            ->where('ext', $ext)->first();
        if (empty($smsCodeRecord)) {
            throw new Exception('该手机号未发送短信');
        }

        if ($smsCodeRecord->code !== $smsCode) {
            throw new Exception('验证码错误');
        }

        return true;
    }
}